package com.leyou.sms.utils;

import com.leyou.sms.common.Config;
import com.leyou.sms.common.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

/**
 * @Author：lidatu
 * @Date： 2019/04/02 星期二 16:26
 * @Description：
 */

@Slf4j
@Component
public class MiaoDiUtils {

    private static String accountSid = Config.ACCOUNT_SID;
    private static String url = Config.BASE_URL;
    private  static String templateid = Config.TEMPLATE_ID;
    public static final long SMS_MIN_INTERVAL_IN_MILLIS = 60000;
    public static final String KEY_PREFIX = "sms:phone";

    @Autowired
    private StringRedisTemplate redisTemplate;

    public void MiaoDiSms(String phone, String code){
        try {
            String key = KEY_PREFIX + phone;
            String body = "accountSid=" + accountSid + "&to=" + phone + "&templateid=" + templateid + "&param=" + code + HttpUtil.createCommonParam();
            // 提交请求
            String result = HttpUtil.post(url, body);
            log.info("result:" + System.lineSeparator() + result);
            //发送短信成功后，写入虚拟机(服务器)中的redis 加前缀 分别不同的key， 指定生产时间为1分钟
            redisTemplate.opsForValue().set(key, String.valueOf(System.currentTimeMillis()), 1, TimeUnit.MINUTES);
        }catch (Exception e){
            log.error("[短信服务] 发送短信异常", phone, e);
        }
    }
}
